package org.freedom.securitytest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 设置角色信息，权限，资源分配
 * @author oneli
 *
 */

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


	//配置Bean
	 @Bean
	    PasswordEncoder passwordEncoder() {
	        return new BCryptPasswordEncoder();
	    }
	 
	 
	 //定义用户名，密码，每个用户拥有的角色
	 //此处是基于内存的认证，也可以在数据库配置好这些信息
	 @Autowired
		public void config(AuthenticationManagerBuilder auth) throws Exception {
//			auth.inMemoryAuthentication()  //开启内存认证
//					.withUser("li")		   //用户名
//					.password("$2a$10$0taMD3JJvlxnp6J8y5OWfO6ANMzyvmnl1JPjJRDK/xJiYbfIWWSSC") //经过 BCrypt加密后的密码
//					.roles("USER")		//用户角色名
//					.and()
////					li 123456 admin 123
//					.withUser("admin")
//					.password("$2a$10$juelhnkt08Pa7BKJwxZCau4Luzq2z9ZP5vAFVc39jtdRQGMnRC3Nq")
//					.roles("ADMIN","USER");
					
			
		}
	
	 //定义每种角色可访问的资源
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		.antMatchers("/","/error").permitAll()          //无需登录认证即可访问
		.antMatchers("/hello").hasRole("USER")			//只有USER角色才能访问/hello
		.antMatchers("/admin").hasRole("ADMIN")			//只有ADMIN角色才能访问/admin
		.anyRequest().authenticated()                   //其余路由都需认证
        .and().formLogin().loginPage("/login").permitAll()           //登录页面无需认证
		.and().logout().permitAll()                                  //注销无需认证
		.and().rememberMe() 					                     //开启记住我功能
		.rememberMeParameter("rememberme").tokenValiditySeconds(60)
		.and()
		//2、登录配置表单认证方式
		.formLogin()
		.loginPage("/login")//自定义登录页面的url
		.usernameParameter("username")//设置登录账号参数，与表单参数一致
		.passwordParameter("password");//设置登录密码参数，与表单参数一致		//记住我有效时间

	}

	

}
